<template>
  <text class="iconfont icon-dizhi" @click="openLocation"></text>
</template>
<script>
export default {
  methods: {
    async openLocation(){
      let isAuth = Boolean
      try {
        isAuth = await this.getUserLocation()
      } catch (bool) {
        isAuth = bool
      }
      console.log(isAuth)
      if(isAuth) {
        this.chooseLocation()
      } else {
        this.openConfirm().then(() => {
          this.chooseLocation();
        })
        .catch(() => {
          uni.showToast({
            title: "你拒绝了授权，无法获得周边信息",
            icon: "none",
            duration: 2000,
          });
        })
      }
    },
    // 拒绝授权后，弹框提示是否手动打开位置授权
    openConfirm() {
      return new Promise((resolve, reject) => {
        uni.showModal({
          title: "请求授权当前位置",
          content: "我们需要获取地理位置信息",
          success: (res) => {
            if (res.confirm) {
              uni.openSetting().then((res) => {
                if (res[1].authSetting["scope.userLocation"] === true) {
                  resolve(); // 打开地图权限设置
                } else {
                  reject();
                }
              });
            } else if (res.cancel) {
              reject();
            }
          },
        });
      });
    },
    getUserLocation() {
      return new Promise((resolve, reject) => {
        uni.authorize({
          scope: "scope.userLocation",
          success: () => {
            resolve(true); // 允许授权
          },
          fail: () => {
            reject(false); // 拒绝授权
          },
        });
      })
    },
    //地图选择地址
    chooseLocation(){
      uni.chooseLocation({
        success: (data)=> {
          if(!data.address) return
          var reg = /.+?(省|市|自治区|自治州|县|区)/g;
          console.log(data.address)
          const arr = data.address.match(reg).toString().split(",")
          let address= [...arr]
          if(address.length==2) {
            address.unshift(address[0])
          }
          
          data.region = address
          console.log(arr)
          data.street = data.address.replace(arr.join(''),'')
          this.$emit('onConfirm',data)
        }
      })
    },
  },
}
</script>
<style scoped>
.icon-dizhi{
  font-size: 45upx;
  width: 50upx;
  height: 50upx;
}
</style>